Skip to content

Add destructuring coalesce #9747

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft

Conversation

bwoebi
Copy link
Member

@bwoebi bwoebi commented Oct 14, 2022

Allowing for [$a ?? $b] = $array;, where $a is assigned $b if the key in the array is null or missing.

RFC: https://wiki.php.net/rfc/destructuring_coalesce

@bwoebi bwoebi force-pushed the destructuring-coalesce branch from 5c8e498 to c79b933 Compare October 14, 2022 14:44
@kandy
Copy link

kandy commented Oct 14, 2022

Is it like?

<?php
['a'=>$a, 'b'=>$b] = [...json_decode('{"a":2}', 1), ...['b'=>'def val']];
var_dump($a, $b);

@bwoebi
Copy link
Member Author

bwoebi commented Oct 15, 2022

@kandy In that particular scenario of a top-level dimension with string keys, where no null values are present, yes.

But array unpacking won't help you with integer keys (because it will re-index them, consecutively), it doesn't allow for any nested destructuring, is not usable inline as a foreach target, and does not handle nulls for you.

@rentalhost
Copy link

I like it!

But what should happen if:

[ $a ?? '123', $b ] = [];
[ $a ?? '123', $b ] = [ 1 ];
[ $a ?? '123', $b ] = [ 1, 2 ];

It also supports ?: operator?

[ $a ?: '123' ] = []; // so $a = '123'
[ $a ?: '123' ] = [ false ]; // so $a = '123'
[ $a ?: '123' ] = [ 456 ]; // so $a = 456

@mvorisek
Copy link
Contributor

I found this PR when looking for another. The RFC was declined, so I think this one can be closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants